package demo1;

import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

class IntCmp implements Comparator<Integer> {
    @Override
    public int compare(Integer o1, Integer o2) {
        return o2-o1;
    }
}

public class Test {

    public static int[] topK1(int[] array, int k) {
        IntCmp intCmp = new IntCmp();
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(intCmp);

        for (int i = 0; i < array.length; i++) {
            priorityQueue.offer(array[i]);
        }

        int[] ret = new int[k];
        for (int i = 0; i < k; i++) {
            ret[i] = priorityQueue.poll();
        }
        return ret;
    }

    public static int[] topK(int[] array, int k) {
        IntCmp intCmp = new IntCmp();
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(k, intCmp);

        int[] ret = new int[k];

        for (int i = 0; i < array.length; i++) {
            if (maxHeap.size() < k) {
                maxHeap.offer(array[i]);
            }else {
                int top = maxHeap.peek();
                if (array[i] < top) {
                    maxHeap.poll();
                    maxHeap.offer(array[i]);
                }
            }
        }

        for (int i = 0; i < k; i++) {
            ret[i] = maxHeap.poll();
        }

        return ret;
    }

    public static void main1(String[] args) {
        int[] array = {29,8,10,48,52,33,59,11,34};
        int[] ret = topK(array, 3);
        System.out.println(Arrays.toString(ret));
    }
}
